<template>
  <div>
    <h1>axios和json综合</h1>
    <input type="button" value="请求和响应都是普通字符串" @click="method01()" />
    <br />
    <input type="button" value="响应数据改成json字符串" @click="method02()" />
    <br />
    <input type="button" value="请求数据也改成json字符串" @click="method03()" />
    <br />
    <hr />
    <h3>好友列表</h3>
    <div id="messageDiv"></div>
    <table
      width="500px"
      cellspacing="0px"
      cellpadding="5px"
      border="1px"
      id="myTable"
    >
      <tr>
        <th>id</th>
        <th>name</th>
        <th>age</th>
      </tr>
      <!-- <tr>
                <td></td>
                <td></td>
                <td></td>
            </tr>-->
    </table>
  </div>
</template>

<script>
import axios from "axios";
export default {
  methods: {
    //1.请求和响应都是普通字符串
    method01() {
      let url = "/jsonDemo01Servlet";
      let params = "name=刘德华&age=44";
      axios.post(url, params).then((resp) => {
        console.log(resp.data);
      });
    },
    //2.请求是普通字符串，响应数据改成json字符串
    method02() {
      let url = "/jsonDemo02Servlet";
      let params = "name=刘德华&age=44";
      axios.post(url, params).then((resp) => {
        console.log(resp.data);
      });
    },
    //3.请求是json字符串，响应数据改成json字符串
    method03() {
      let url = "/jsonDemo03Servlet";
      //json字符串
      let params = {
        id: "100",
        name: "张三",
        age: "18",
      };
      axios.post(url, params).then((resp) => {
        console.log(resp.data);
        let obj = resp.data;
        if (obj.flag) {
          //响应成功，遍历集合
          let arr = obj.valueData;
          let content = "";
          for (let friend of arr) {
            content += `<tr>
                          <td>${friend.id}</td>
                          <td>${friend.name}</td>
                          <td>${friend.age}</td>
                        </tr>`;
          }
          //将查询出的结果写入页面
          document.getElementById("messageDiv").innerHTML = obj.message;
          document.getElementById("myTable").innerHTML += content;
        } else {
          //如果响应失败，返回提示信息
          document.getElementById("messageDiv").innerHTML = obj.message;
        }
      });
    },
  },
};
</script>

<style>
</style>
